<template>
  <div class="zyb">
    <div class="header">
      <img
        v-if="!isFromAndroid"
        src="@/assets/images/goBackImg.png"
        class="back"
        alt="header"
        @click="goBack"
      />
      <img
        src="@/assets/images/home.png"
        class="back home"
        alt="header"
        @click="goHome"
      />
    </div>
    <div class="main">
      <div class="info-container">
        <div class="left">
          <div class="left-top">
            <span>{{ localInfo.title }}</span>
            <template v-if="localInfo.volunteerId">
              <img
                class="edit-icon"
                :src="editIcon"
                alt=""
                @click="changeTitleName"
              />
              <img
                class="star-icon"
                :src="localInfo.isCollect == 1 ? starFill : starUnFill"
                alt=""
                @click="handleCollect"
              />
              <div class="export-btn" @click="handleExport">
                <span>导出</span>
                <img class="icon" :src="exportIcon" alt="" />
              </div>
            </template>
          </div>
          <div class="left-bottom">
            <div class="bottom-left">
              {{ localInfo.schoolLevelName }} / {{ localInfo.regionName }} /
              {{ localInfo.subjectShortName }}
              / {{ localInfo.score }}分 / {{ localInfo.rankNum }}名
            </div>
          </div>
        </div>
        <div class="right">
          <div class="right-item" @click="goAllMajor">
            <span>全部可选专业</span>
            <img class="icon" :src="whiteArrowRight" alt="" />
          </div>
          <div class="right-item" @click="goMyVolunteerList">
            <span>其他志愿表</span>
            <img class="icon" :src="whiteArrowRight" alt="" />
          </div>
        </div>
      </div>
      <div class="table-container">
        <VolunteerList
          ref="volunteerListRef"
          :currentWishDetail="currentWishDetail"
          @volunteerCurInfoFn="getVolunteerCurInfoFn"
        ></VolunteerList>
      </div>
    </div>
    <EditNamePopup
      v-model:showPopup="showChangeDialog"
      :name="localInfo.title"
      @handleConfirm="onConfirmChange"
    ></EditNamePopup>

    <PageLoading v-if="showLoading"></PageLoading>
    <QrCode v-model:show="showQrCode" :url="qrCodeUrl"></QrCode>
  </div>
</template>

<script setup>
import {
  onBeforeMount,
  onMounted,
  onUnmounted,
  ref,
  computed,
  defineAsyncComponent,
} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useVolunteerStore } from '@/store/volunteer';
import { showToast } from 'vant';
import { onBackPressed } from '@/utils/androidFn.js';
import provinceData from '@/utils/provinceData.js';
import { subjectMap } from '@/utils/subjectData';
import editIcon from '@/assets/images/editPenWhite.png';
import starFill from '@/assets/images/starFill.png';
import starUnFill from '@/assets/images/starUnFill.png';
import whiteArrowRight from '@/assets/images/whiteArrowRight.png';
import exportIcon from '@/assets/images/exportIcon.png';

import {
  getVolunteerCurInfo,
  volunteerUpdate,
  volunteerCollect,
  volunteerExport,
  volunteerExportRes,
  getVolunteerRegion,
} from '@/api/volunteer';

const EditNamePopup = defineAsyncComponent(() =>
  import('./components/EditNamePopup.vue')
);
const VolunteerList = defineAsyncComponent(() =>
  import('./components/VolunteerList.vue')
);
const PageLoading = defineAsyncComponent(() =>
  import('./components/pageLoading.vue')
);
const QrCode = defineAsyncComponent(() => import('./components/QrCode.vue'));

defineOptions({
  name: 'VolunTeerDetail',
});

const route = useRoute();
const router = useRouter();
const store = useVolunteerStore();
const defaultBatchType = computed(() => store.defaultBatchType);
const volunteerInfo = computed(() => store.volunteerInfo);
const totalSelectNum = ref(1); // 已使用次数
const totalVolunteerNum = ref(45); // 全部次数
const rushSteadyGroupNum = ref({}); // 冲稳组
const rushSteadyGroupTotalNum = ref(0); // 冲稳组总人数

const cateTypeMap = {
  30: '本科',
  10: '专科',
};

const subjectNameMap = {
  11: '物',
  12: '历',
  13: '生',
  14: '化',
  15: '政',
  16: '地',
};

const goBack = () => {
  if (route.query.to) {
    router.replace(route.query.to);
  } else {
    router.go(-1);
  }
};

const goHome = () => {
  if (isFromAndroid.value) {
    onBackPressed(router);
  } else {
    router.replace({
      path: '/home',
    });
  }
};

const goAllMajor = () => {
  router.push({
    path: '/collegeVolunteer',
  });
};

const goMyVolunteerList = () => {
  router.push({
    path: '/myVolunteerTable',
    query: {
      fromType: 'vue',
    },
  });
};

const showQrCode = ref(false);
const qrCodeUrl = ref('');
const showLoading = ref(false);
const handleExport = async () => {
  showLoading.value = true;

  try {
    // 先检查是否已经有生成的导出文件
    const checkParams = {
      volunteerId: volunteerId.value,
    };
    const checkRes = await volunteerExportRes(checkParams);

    if (checkRes.code === 200 && checkRes.data.status === 1) {
      const { fileUrl } = checkRes.data;
      // 已经有生成好的文件，直接显示
      showLoading.value = false;
      qrCodeUrl.value = fileUrl;
      showQrCode.value = true;
    } else if (checkRes.code === 200 && checkRes.data.status === 0) {
      // 正在生成中，开始轮询
      volunteerExportResFn();
    } else {
      // 没有生成过或生成失败，开始生成
      const params = {
        volunteerId: volunteerId.value,
      };
      const res = await volunteerExport(params);
      if (res.code == 200) {
        setTimeout(() => {
          volunteerExportResFn();
        }, 4000);
      } else {
        showLoading.value = false;
        showToast('网络异常，请稍后重试');
      }
    }
  } catch (error) {
    showLoading.value = false;
    showToast('网络异常，请稍后重试');
  }
};

const volunteerExportResFn = async () => {
  let attemptCount = 0;
  const maxAttempts = 5;
  const intervalTime = 3000;

  const pollExportResult = async () => {
    try {
      const params = {
        volunteerId: volunteerId.value,
      };
      const res = await volunteerExportRes(params);

      if (res.code !== 200) {
        throw new Error(`请求失败: ${res.message || '未知错误'}`);
      }

      const { status } = res.data; // status == 0 进行中  1 成功 2 失败

      switch (status) {
        case 1: // 成功
          showLoading.value = false;
          qrCodeUrl.value = res.data.fileUrl;
          showQrCode.value = true;
          return;

        case 2: // 失败
          showLoading.value = false;
          showToast('导出失败，请稍后重试');
          return;

        case 0: // 进行中
        default:
          // 继续轮询
          attemptCount++;
          if (attemptCount < maxAttempts) {
            setTimeout(pollExportResult, intervalTime);
          } else {
            // 达到最大尝试次数，停止轮询
            showLoading.value = false;
            showToast('导出超时，请稍后重试');
          }
          break;
      }
    } catch (error) {
      // 发生错误，停止轮询
      showLoading.value = false;
      showToast('导出失败，请稍后重试');
    }
  };

  // 开始轮询
  pollExportResult();
};

let currentWishDetail = ref({});
const volunteerId = ref(''); // 志愿表id
const getVolunteerCurInfoFn = async () => {
  const params = {
    rankNum: volunteerInfo.value.position,
    subject: volunteerInfo.value.relSubject,
    score: volunteerInfo.value.score,
    regionId: volunteerInfo.value.regionId,
    batchType: defaultBatchType.value,
  };
  const res = await getVolunteerCurInfo(params);
  if (res.code == 200) {
    getNames(res.data);
    totalSelectNum.value = res.data.totalSelectNum;
    totalVolunteerNum.value = res.data.totalVolunteerNum;
    volunteerId.value = res.data.volunteerId;

    rushSteadyGroupNum.value = res.data.rushSteadyGroupNum;
    rushSteadyGroupTotalNum.value =
      res.data.rushSteadyGroupNum[10] +
      res.data.rushSteadyGroupNum[20] +
      res.data.rushSteadyGroupNum[30];
    currentWishDetail.value = res.data;
  }
};

const localInfo = ref(volunteerInfo.value);
const getNames = (data) => {
  data.schoolLevelName = cateTypeMap[data.cateType];
  data.subjectShortName = data.subject
    .split(',')
    .map((item) => subjectNameMap[item])
    .join('');
  Object.assign(localInfo.value, data);
};

const showChangeDialog = ref(false);

const changeTitleName = async () => {
  showChangeDialog.value = true;
};

const handleCollect = async () => {
  const params = {
    volunteerId: volunteerId.value,
    isCollect: localInfo.value.isCollect == 1 ? 2 : 1,
  };
  const res = await volunteerCollect(params);
  if (res.code == 200) {
    showToast(params.isCollect == 1 ? '收藏成功！' : '已取消收藏');
    localInfo.value.isCollect = params.isCollect;
  }
};

const onConfirmChange = async (name) => {
  const params = {
    volunteerId: volunteerId.value,
    title: name,
  };
  const res = await volunteerUpdate(params);
  if (res.code == 200) {
    localInfo.value.title = name;
  }
};

const volunteerListRef = ref(null);
const closeAllTooltips = () => {
  if (volunteerListRef.value) {
    volunteerListRef.value.closeAllTooltips();
  }
};

const getSubjectName = (...ids) => {
  // 处理参数：扁平化 + 拆分逗号分隔的字符串
  const idArray = ids
    .flatMap((id) => {
      // 如果是字符串且包含逗号，分割成数组并去除空格
      if (typeof id === 'string' && id.includes(',')) {
        return id.split(',').map((s) => s.trim());
      }
      return id;
    })
    .flat(Infinity) // 彻底扁平化嵌套数组
    .map((id) => Number(id)) // 转为数字
    .filter((id) => !isNaN(id) && subjectMap[id]); // 过滤无效和非映射 ID

  // 获取学科全名并用中文顿号连接
  const result = idArray.map((id) => subjectMap[id]).join('、'); // 中文顿号分隔

  return result;
};

const getProvinceName = (code) => {
  return provinceData.find((item) => item.code == code)?.name;
};

const getSubjectType = (subject) => {
  return subject.split(',')[0];
};

const provinces = ref([]);
const getVolunteerRegionFn = async () => {
  const params = {
    platform: 4,
  };
  const res = await getVolunteerRegion(params);
  if (res.code == 200) {
    provinces.value = [];
    res.data.forEach((item) => {
      provinces.value.push({
        ...item,
        name: item.regionName,
        value: item.regionId,
      });
    });
    store.setProvinces(provinces.value);
  }
};

const getDataFromAndroid = () => {
  const {
    batchType,
    cateType,
    rankNum,
    regionId,
    subject,
    score,
    totalSelectNum: num1,
    totalVolunteerNum: num2,
  } = route.query;
  const temp = store.provinces.find((_item) => _item.value == regionId);
  const params = {
    relSubject: subject,
    subjectTypeDesc: getSubjectName(subject),
    subjectType: getSubjectType(subject),
    score,
    regionId,
    position: rankNum,
    regionName: getProvinceName(regionId),
    schoolLevelName: cateType == 30 ? '本科' : '专科',
    batchType,
    planYear: temp ? temp?.planYear : '',
  };
  totalSelectNum.value = num1;
  totalVolunteerNum.value = num2;
  store.setVolunteerInfo(params);
  store.setDefaultBatchType(batchType);
};

const isFromAndroid = ref(false);
onBeforeMount(async () => {
  if (route.query.fromType == 'android') {
    isFromAndroid.value = true;
    await getVolunteerRegionFn();
    getDataFromAndroid();
    await getVolunteerCurInfoFn();
  }
});

onMounted(() => {
  if (!isFromAndroid.value) {
    getVolunteerCurInfoFn();
  }
  // 监听页面的滚动事件，调用子组件closeAllTooltips方法。
  document.addEventListener('scroll', closeAllTooltips);
});

onUnmounted(() => {
  document.removeEventListener('scroll', closeAllTooltips);
});
</script>

<style lang="scss" scoped>
.zyb {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(180deg, #3d6bfb 0%, rgba(223, 240, 255, 0) 100%);
  .header {
    display: flex;
    align-items: center;
    position: relative;
    padding: 30px 32px 0 32px;
    .back {
      width: 40px;
      height: 40px;
      margin-right: 24px;
    }
    .title {
      height: 40px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 30px;
      color: #ffffff;
      line-height: 40px;
    }
  }
  .main {
    .info-container {
      padding: 16px 32px 12px 32px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      position: sticky;
      top: 0;
      z-index: 900;
      background: linear-gradient(180deg, #4d77fb 0%, #5c83fb 100%);
      .left {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        justify-content: space-between;
        .left-top {
          font-family: PingFang-SC, PingFang-SC;
          font-weight: bold;
          font-size: 38px;
          color: #ffffff;
          display: flex;
          align-items: center;
          .edit-icon {
            width: 32px;
            height: 32px;
            padding: 12px;
          }
          .star-icon {
            margin-left: 12px;
            width: 28px;
            height: 28px;
            padding: 12px;
          }
          .export-btn {
            margin-left: 30px;
            font-size: 24px;
            color: $primary-color;
            font-weight: bold;
            padding: 8px 28px;
            background: #ffffff;
            border-radius: 10px;
            display: flex;
            align-items: center;
            .icon {
              width: 24px;
              height: 24px;
              margin-left: 14px;
            }
          }
        }
        .left-bottom {
          margin-top: 15px;
          height: 22px;
          font-weight: bold;
          font-size: 22px;
          color: #ffffff;
          line-height: 22px;
        }
      }
      .right {
        font-size: 24px;
        display: flex;
        .right-item {
          color: #fff;
          font-weight: bold;
          display: flex;
          align-items: center;
          margin-right: 32px;
          &:last-child {
            margin-right: 0;
          }
          .icon {
            width: 16px;
            height: 16px;
            margin-left: 10px;
          }
        }
      }
    }

    .table-container {
      padding: 6px 32px 0 32px;
      width: 100%;
      height: calc(100% - 220px);
      box-sizing: border-box;
    }
  }
  .fix-bottom {
    width: 100%;
    height: 95px;
    background: #ffffff;
    box-shadow: 0px 0px 4px 0px rgba(188, 188, 188, 0.5);
    position: fixed;
    bottom: 0;
    padding: 22px 16px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    .other-zyb {
      width: 130px;
      height: 24px;
      background: #f7f8fa;
      border-radius: 4px;
      padding: 6px 8px 5px 10px;
      box-sizing: border-box;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #000000;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      .arrow-down {
        width: 8px;
        height: 8px;
      }
    }
    .export-zyb {
      width: 119px;
      height: 40px;
      background: #f75a3e;
      border-radius: 6px;
      font-family: PingFang-SC, PingFang-SC;
      font-weight: bold;
      font-size: 18px;
      color: #ffffff;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
    }
  }
}

.custom-field :deep(.van-field__control) {
  background-color: #f7f8fa; /* 自定义背景色 */
}
.custom-field :deep(.van-field__label) {
  width: 40%;
}
</style>
